package com.microclouddisks.controller;

import com.amazonaws.services.s3.AmazonS3;
import com.microclouddisks.entity.diskUser;
import com.microclouddisks.entity.folder;
import com.microclouddisks.functions.AWS_S3;
import com.microclouddisks.functions.queryIcon;
import com.microclouddisks.service.mainService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class mainController {

    @Autowired
    private mainService mainservice;

    @RequestMapping(value = "/main")
    public String mains(HttpSession session, Model model) {
        diskUser user = (diskUser) session.getAttribute("diskuser");
        if (user.getUsermail() != null) {
            System.out.println("Controller : main() : session " + user.getUsermail());
            List<folder> folderlist = mainservice.folderQuery(user.getUsermail(), user.getUsermail());
            model.addAttribute("folderlist", folderlist);
            return "main";
        } else {
            System.out.println("Controller : main() : session is null " + user.getUsermail());
            return "login";
        }
    }

    // 处理上传的
    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response, HttpSession session,
                       @RequestParam("file") CommonsMultipartFile file,
                       @RequestParam("filepaths") String filepaths) throws IOException {
        System.out.println("---------------------->" + filepaths);
        PrintWriter out;
        String filesizetoString = null;
        boolean flag = false;
        if (!file.isEmpty()) {
            String tempPath = "H:\\IDEAWorkspace\\MicroCloudDisks\\src\\main\\webapp\\uploads\\";
//            String tempPath = "C:\\temp\\";

//            String filepaths = request.getParameter("filepath");
            String filename = file.getOriginalFilename();
//            String filetype = file.getContentType();
            double filesize = file.getSize();
            diskUser user = (diskUser) session.getAttribute("diskuser");

            if (filepaths == null || filepaths.length() == 0) {
                filepaths = user.getUsermail();
            }

//            File tempfile = new File(tempPath);
//            if (!tempfile.exists()) {
//                tempfile.mkdirs();
//            }

            try {
                //本地临时文件
                File tempfile = new File(tempPath + filepaths + "\\"
                        + file.getOriginalFilename());
                if (!tempfile.exists()) {
                    tempfile.mkdirs();
                }
                file.transferTo(tempfile);
                //s3
                String s3filePath = filepaths.replace("\\", "/") + "/" + filename;
                System.out.println("s3filepath 1  :" + s3filePath);

//                File file2 = new File("");
//                DiskFileItem fi = (DiskFileItem) file.getFileItem();
//                File f = fi.getStoreLocation();
                System.out.println("s3filepath 3  :");
                flag = true;
                out = response.getWriter();
                if (flag == true) {
                    out.print("1");
                } else {
                    out.print("2");
                }

                int index = filename.lastIndexOf(".");
                String filetype2 = filename.substring(index + 1, filename.length());

                if (filesize >= 0 && filesize < 1024) {//文件大小小于 1K 字节级别
                    filesizetoString = String.valueOf(filesize) + " Bytes";
                } else if (filesize >= 1024 && filesize < 1048576) { //K
                    filesize = filesize / 1024;
                    filesizetoString = String.format("%.2f", filesize) + " KB";
                } else if (filesize >= 1048576 && filesize < 1073741824) {
                    filesize = filesize / 1048576;
                    filesizetoString = String.format("%.2f", filesize) + " MB";
                } else {
                    filesize = filesize / 1073741824;
                    filesizetoString = String.format("%.2f", filesize) + " GB";
                }

                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = formatter.format(date);
                folder folder = new folder();
                folder.setFolderid(filepaths + "-" + time);
                folder.setFoldername(filename);
                folder.setUsermail(user.getUsermail());
                folder.setUpdatetime(time);
                folder.setSizes(filesizetoString);
                folder.setFiletype(filetype2);
                folder.setParent(filepaths);
                folder.setNum(0);
                queryIcon iconquery = new queryIcon();
                folder.setIcon(iconquery.iconQuery(filetype2));
                folder.setFilepath(s3filePath);


                //s3
                AWS_S3 aws_s3 = new AWS_S3();
                AmazonS3 s3 = aws_s3.CreateS3Client();
                String s3url = aws_s3.getFileURL(s3, "microclouds", s3filePath);
                folder.setS3url(s3url);
                mainservice.creatFolder(folder);

                aws_s3.UpdateFile(tempfile, "microclouds", s3filePath, s3);
                tempfile.delete();
                System.out.println("save database !");
//                FileUtils.copyInputStreamToFile(file.getInputStream(),
//                        new File(path, file.getOriginalFilename()));
                flag = true;
            } catch (Exception e) {
            }

        }

//        out = response.getWriter();
//        if (flag == true) {
//            out.print("1");
//        } else {
//            out.print("2");
//        }

    }


    @RequestMapping(value = "/newFolder")
    public String creatFolder(HttpServletRequest request, HttpSession session) {
        String filepath = request.getParameter("filepath");
        String usermail = request.getParameter("usermail");
        String foldername = request.getParameter("foldername");
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(date);
        if (foldername == null || foldername.equals("") || foldername.length() == 0) {
            foldername = "新建文件夹" + "_" + time;
        }
        if (filepath == null) {
            filepath = usermail;
        }
// else {
//        这里切割文件路径
//            int index = filepath.lastIndexOf("*");
//            parent = filepath.replace("*", "\\");
//            System.out.println("----切割完成之后的path : " + parent + "-" + filepath);
//        }

        String folderPath = filepath + "/" + foldername;
        AWS_S3 aws_s3 = new AWS_S3();
        AmazonS3 s3 = aws_s3.CreateS3Client();
        String result = aws_s3.CreateFolder("microclouds", folderPath, s3);
        System.out.println("create folder success! result : " + filepath);
//        File file = new File("H:\\IDEAWorkspace\\MicroCloudDisks\\src\\main\\webapp\\uploads\\"
//                + filepath + "\\" + foldername);
//        if (!file.exists()) {
//            file.mkdir();
//        }
        folder folder = new folder();
        folder.setFolderid(filepath + "-" + time);
        folder.setFoldername(foldername);
        folder.setSizes("-");
        folder.setUpdatetime(time);
        folder.setUsermail(usermail);
        folder.setFiletype("folder");
        folder.setParent(filepath);//todo
        folder.setNum(0);
        folder.setIcon("img/folder6.jpg");
        folder.setS3url("-");
        folder.setFilepath(folderPath);
        mainservice.creatFolder(folder);
        session.setAttribute("folder", folder);
        return "redirect:main";
    }

    @RequestMapping(value = "/deleteFolder")
    public String deleteFolder(HttpServletRequest request) {
        String filepath = request.getParameter("filepath");
        String usermail = request.getParameter("usermail");
        System.out.println("------>controller : deleteFolder :  usermail : " + usermail + "foldername : ");
//        File file = new File("H:\\IDEAWorkspace\\MicroCloudDisks\\src\\main\\webapp\\uploads\\"
//                + filepath + "\\" + foldername);
//        if (file.exists()) {
//            file.delete();
//        }

        String longs = request.getParameter("deletefoldername");
        System.out.println("long :" + longs);
        String[] fileLists = longs.split("\\|");

        folder folder = new folder();
        for (String s : fileLists) {
            folder = mainservice.folderQueryById(s);
            mainservice.trashInsert(folder);
            mainservice.deleteFileById(s);
            System.out.println("fileList : " + s);
        }

//        folder folder = new folder();
//        folder.setParent(filepath);
//        folder.setFoldername(foldername);
//        folder.setUsermail(usermail);
//        mainservice.deleteFolder(folder);
//        System.out.println("------>controller : deleteFolder : " + filepath + "-" + foldername);
        return "redirect:main";
    }

    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(HttpSession session,
                                           @RequestParam("filename") String filename,
                                           @RequestParam("filepath") String filepath,
                                           Model model) throws Exception {

        System.out.println("download service !");
//        diskUser user = (diskUser) session.getAttribute("diskuser");
        File tempfile = new File("H:\\IDEAWorkspace\\MicroCloudDisks\\src\\main\\webapp\\temp\\"
        );
        if (!tempfile.exists()) {
            tempfile.mkdir();
        }

        AWS_S3 aws_s3 = new AWS_S3();
        System.out.println("download service 2");
        AmazonS3 s3 = aws_s3.CreateS3Client();
        System.out.println("download service 3");
        String url = aws_s3.getFileURL(s3, "microclouds", filepath);
        System.out.println("download service four" + filepath);
        File file = aws_s3.downloadFileFromURL
                (url, filename, "H:\\IDEAWorkspace\\MicroCloudDisks\\src\\main\\webapp\\temp\\");
        // 下载文件的路径
//        String path = request.getServletContext().getRealPath("/img/");
//        File file = new File(path + File.separator + filename);
        System.out.println("download service 5");
        HttpHeaders headers = new HttpHeaders();

        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 201 HttpStatus.CREATED
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/detailFilesList")
    public String detailFilesList(HttpSession session, Model model, HttpServletRequest request) {
        diskUser user = (diskUser) session.getAttribute("diskuser");
        String filepath = request.getParameter("filepath");
        System.out.println("==============>  path : " + filepath);
        String detailFilesListName = request.getParameter("detailFilesListName");
        if (user.getUsermail() != null) {
            System.out.println("------> Controller : detailFilesList() :  " + detailFilesListName);

            int index = filepath.lastIndexOf("*");
            filepath = filepath.replace("*", "\\");
//            parent = filepath.substring(0, index);
            System.out.println("----切割完成之后的path : " + filepath + "-" + filepath);

            List<folder> folderlist = mainservice.folderQuery(user.getUsermail(), filepath);
            model.addAttribute("filepath", filepath);
            model.addAttribute("nowfolder", detailFilesListName);
            model.addAttribute("folderlist", folderlist);
            return "main";
        } else {
            System.out.println("------>  Controller : main() : session is null ");
            return "login";
        }
    }


    @RequestMapping("/userCenter")
    public String userCenter(HttpSession session, Model model) {

        return "userCenter";
    }

}
